package com.yzk.train.business.service;

import com.yzk.train.business.entity.ConfirmOrder;
import com.yzk.train.business.entity.DailyTrainSeat;
import com.yzk.train.business.entity.DailyTrainTicket;
import com.yzk.train.business.enums.ConfirmOrderStatusEnum;
import com.yzk.train.business.feign.MemberFeign;
import com.yzk.train.business.mapper.ConfirmOrderMapper;
import com.yzk.train.business.mapper.DailyTrainTicketMapper;
import com.yzk.train.business.request.ConfirmOrderTicketReq;
import com.yzk.train.common.request.MemberTicketReq;
import com.yzk.train.common.response.Result;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AfterConfirmOrderService {

    private static final Logger LOG = LoggerFactory.getLogger(AfterConfirmOrderService.class);

    @Resource
    private DailyTrainSeatService dailyTrainSeatService;

    @Resource
    private DailyTrainTicketMapper dailyTrainTicketMapper;

    @Resource
    private MemberFeign memberFeign;

    @Resource
    private ConfirmOrderMapper confirmOrderMapper;

    /**
     * 选中座位后事务处理
     * 1、座位表修改售卖情况sell
     * 2、余票详情表修改余票
     * 3、为会员增加购票记录
     * 4、更新确认订单为成功
     *
     * @param dailyTrainTicket 余票信息
     * @param finalSeatList 最终选座结果
     * @param tickets 购票信息
     * @param confirmOrder 订单信息
     */
    @GlobalTransactional
    public void afterDoConfirm(DailyTrainTicket dailyTrainTicket, List<DailyTrainSeat> finalSeatList,
                               List<ConfirmOrderTicketReq> tickets, ConfirmOrder confirmOrder) {
        for (int j = 0; j < finalSeatList.size(); j++) {
            DailyTrainSeat dailyTrainSeat = finalSeatList.get(j);
            // 1、座位表修改售卖情况sell
            DailyTrainSeat seatForUpdate = new DailyTrainSeat();
            seatForUpdate.setId(dailyTrainSeat.getId());
            seatForUpdate.setSell(dailyTrainSeat.getSell());
            seatForUpdate.setUpdateTime(new Date());
            dailyTrainSeatService.update(seatForUpdate);

            // 2、余票详情表修改余票
            // minStartIndex = startIndex - 往前碰到的最后一个0
            // maxStartIndex = endIndex - 1
            // minEndIndex = startIndex + 1
            // maxEndIndex = endIndex + 往后碰到的最后一个O
            Integer startIndex = dailyTrainTicket.getStartIndex();
            Integer endIndex = dailyTrainTicket.getEndIndex();
            char[] charArray = seatForUpdate.getSell().toCharArray();
            Integer maxStartIndex = endIndex - 1;
            Integer minStartIndex = 0;
            for (int i = startIndex - 1; i >= 0; i--) {
                char c = charArray[i];
                if (c == '1') {
                    minStartIndex = i + 1;
                    break;
                }
            }
            LOG.info("影响的出发站区间：{}", minStartIndex + "-" + maxStartIndex);
            Integer minEndIndex = startIndex + 1;
            Integer maxEndIndex = seatForUpdate.getSell().length();
            for (int i = endIndex; i < seatForUpdate.getSell().length(); i++) {
                char c = charArray[i];
                if (c == '1') {
                    maxEndIndex = i;
                    break;
                }
            }
            LOG.info("影响的到达站区间：{}", minEndIndex + "-" + maxEndIndex);
            dailyTrainTicketMapper.updateTicketCountBySell(
                    dailyTrainSeat.getDate(),
                    dailyTrainSeat.getTrainCode(),
                    dailyTrainSeat.getSeatType(),
                    minStartIndex,
                    maxStartIndex,
                    minEndIndex,
                    maxEndIndex
            );

            // 3、为会员增加购票记录
            MemberTicketReq memberTicketReq = new MemberTicketReq();
            memberTicketReq.setMemberId(confirmOrder.getMemberId());
            memberTicketReq.setPassengerId(tickets.get(j).getPassengerId());
            memberTicketReq.setPassengerName(tickets.get(j).getPassengerName());
            memberTicketReq.setTrainDate(dailyTrainTicket.getDate());
            memberTicketReq.setTrainCode(dailyTrainTicket.getTrainCode());
            memberTicketReq.setCarriageIndex(dailyTrainSeat.getCarriageIndex());
            memberTicketReq.setSeatRow(dailyTrainSeat.getRow());
            memberTicketReq.setSeatCol(dailyTrainSeat.getCol());
            memberTicketReq.setStartStation(dailyTrainTicket.getStart());
            memberTicketReq.setStartTime(dailyTrainTicket.getStartTime());
            memberTicketReq.setEndStation(dailyTrainTicket.getEnd());
            memberTicketReq.setEndTime(dailyTrainTicket.getEndTime());
            memberTicketReq.setSeatType(dailyTrainSeat.getSeatType());
            Result<Object> result = memberFeign.save(memberTicketReq);
            LOG.info("远程调用Member保存车票接口，返回：{}", result);

            // 4、更新确认订单为成功
            ConfirmOrder confirmOrderForUpdate = new ConfirmOrder();
            confirmOrderForUpdate.setId(confirmOrder.getId());
            confirmOrderForUpdate.setUpdateTime(new Date());
            confirmOrderForUpdate.setStatus(ConfirmOrderStatusEnum.SUCCESS.getCode());
            confirmOrderMapper.updateByPrimaryKeySelective(confirmOrderForUpdate);
        }
    }

}
